<template>
  <g-form ref="form" :model="form" :rules="ruleValidate">
    <g-form-item label="用户名" prop="name">
      <g-input v-model="form.name" />
    </g-form-item>
    <g-form-item label="邮箱" prop="mail">
      <g-input v-model="form.mail" />
    </g-form-item>
    <g-form-item label="用户协议" prop="agree">
      <g-checkbox v-model="form.agree" />
    </g-form-item>
    <g-form-item label="用户协议" prop="multiple">
      <g-checkbox-group v-model="form.multiple">
        <g-checkbox label="option1">选项 1</g-checkbox>
        <g-checkbox label="option2">选项 2</g-checkbox>
        <g-checkbox label="option3">选项 3</g-checkbox>
        <g-checkbox label="option4">选项 4</g-checkbox>
      </g-checkbox-group>
    </g-form-item>
    <g-form-item>
      <button style="margin: 10px" @click="onSubmit">提交</button>
      <button @click="onReset">重置</button>
    </g-form-item>
  </g-form>
</template>

<script>
export default {
  data() {
    return {
      form: {
        name: '22',
        mail: '',
        agree: '',
        multiple: [],
      },
      ruleValidate: {
        name: { required: true, message: '用户名不能为空', trigger: 'blur' },
        mail: [
          { required: true, message: '邮箱不能为空', trigger: 'blur' },
          { type: 'email', message: '邮箱格式不正确', trigger: 'blur' },
        ],
        agree: {
          required: true,
          type: 'boolean',
          message: '请勾选我已阅读并同意用户协议',
          trigger: 'change',
        },
        multiple: {
          required: true,
          type: 'array',
          message: '请勾选我已阅读并同意用户协议',
          trigger: 'change',
        },
      },
    }
  },
  methods: {
    onSubmit() {
      console.log('submit', this.form, this.$refs.form)
      // 普通回调
      this.$refs.form.validate(valid => {
        if (valid) {
          console.log('提交成功')
        } else {
          console.log('表单校验失败')
        }
      })
      // Promise 回调
      // let validate = this.$refs.form.validate();
      // validate
      //   .then((valid) => {
      //     console.log(valid);
      //   })
      //   .catch(() => {});
    },
    onReset() {
      console.log('reset', this.$refs.form)
      this.$refs.form.resetFields()
    },
  },
}
</script>
